package THREADS;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

import DeportManage.NotFormatParcelIDException;
import DeportManage.OutRangeOfDaysException;
import DeportManage.Parcel;
import MVC.DataObserver;

public class ParcelThread extends Thread{
	private DataObserver data_observer;
	
	/**
	 * Constructor to create an object of parcel thread with Observer 
	 * @param data_observer an object of Observer interface
	 * @return 
	 */
	public ParcelThread(DataObserver data_observer){
		this.data_observer = data_observer;
	}

	/**
	 * Method to run the thread methods
	 */
	public void run(){
		try{
			File inputFile = new File("New Parcel.txt");
			Scanner sc=new Scanner(inputFile);
				while(sc.hasNextLine()){
					String readingLine = sc.nextLine();	
					if (readingLine.length() != 0)
						if(readbyLineforParcel(readingLine) != null)
						data_observer.addParcl(readbyLineforParcel(readingLine));// read the data line-by-line
				}
			}				
		
		catch(FileNotFoundException fnf){//boolean whether there is the file.
			System.out.println("The New Parcel.txt is not found! ");
			System.exit(0);
		}
	}
	/**
	 * Method to collect the data line-by-line and put into Parcel List
	 * @param readingLine String a line of data from data file
	 */
	private Parcel readbyLineforParcel(String readingLine){
		String id_parcel ="";
		int days = 0;
		double weight = 0;
		double width = 0;
		double length = 0;
		double height = 0;
		try{
			String parcelstring [] = readingLine.split(",");

			@SuppressWarnings("unused")
			int numberOfID = Integer.parseInt(parcelstring[0].substring(1));
				
			id_parcel = parcelstring[0];
			days = Integer.parseInt(parcelstring[1]);
			weight = Double.parseDouble(parcelstring[2]);
			String dimension [] = parcelstring[3].split("x");
			width = Double.parseDouble(dimension[0]);
			length = Double.parseDouble(dimension[1]);
			height = Double.parseDouble(dimension[2]);
			Parcel parcel = new Parcel(id_parcel,days,weight,height,width,length);
			return parcel;			
		}
		catch(NumberFormatException nfe){
			System.out.println(nfe.getMessage());
			return null;
		}
		catch(ArrayIndexOutOfBoundsException oae){
			System.out.println("The readling is out of BOUND: " + readingLine);
			return null;
		} catch (NotFormatParcelIDException nfpie) {
			System.out.println(nfpie.getMessage());
			return null;
		} catch (OutRangeOfDaysException orode) {
			System.out.println(orode.getMessage());
			return null;
		}
	}
	
	
	
}
